import axios from 'axios'
import router from '../router'
import store from '../store'

import { showNoti } from './Util'
import { BoxType } from 'assets/js/Constant'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const loginUrl = store.state.loginUrl || "/login";

axios.defaults.withCredentials = true;
const $axios = axios.create({
	baseURL: process.env.VUE_APP_ROOT_URL
});

NProgress.configure({ showSpinner: false })

/**********拦截器 ===> 请求****************/
$axios.interceptors.request.use(config => {
	NProgress.start();

	// config.data = {
	// 	...config.data,
	// 	token: store.state.token
	// }

	if (config.method === 'get') {
		config.params = { ...config.data };
	}

	config.headers.token = store.state.token

	return config
}, error => {
	showNoti(JSON.stringify(error), BoxType.ERROR)
	Promise.reject(error)
});

/**********拦截器 ===> 响应****************/
$axios.interceptors.response.use(
	response => {
		NProgress.done();

		if (response.headers.token) {
			store.commit("updateToken", response.headers.token);
		}

		if (!response.data.meta.success) {
			showNoti(response.data.meta.message, BoxType.ERROR)
			if (response.data.meta.code === 2001) {
				router.replace({
					path: loginUrl,
					query: {
						redirect: router.currentRoute._value.fullPath
					}
				})
			}
		} else
			return response.data.data;
	},
	error => {
		NProgress.done();

		let text = "";
		let meta = error.response.data.meta;

		if (meta) {
			if (meta.code === 2001) {
				//重新登录
				router.replace({
					path: loginUrl,
					query: {
						redirect: router.currentRoute._value.fullPath
					}
				})
			}
			text = meta.message;
		} else {
			text = error.response.data.message
		}

		showNoti(text || '出现错误', BoxType.ERROR)

		return Promise.reject(error)
	}
);

export default $axios
